home *** CD-ROM | disk | FTP | other *** search
- * Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
- * The C++ Answer Book */
- * Tony Hansen */
- * All rights reserved. */
- / class "extensible array"
- / This class maintains a character array
- / which dynamically lengthens. The array
- / begins with a fixed size allocated statically,
- / but goes into the heap when the bounds
- / of that array are exceeded.
- include <string.h>
-
- onst int extstartsize = 50; // initial size of buffer
-
- lass extarray
-
- char buf[extstartsize]; // starting buffer
- char *base; // ptr to current buffer
- char *end; // end of current buffer
- char *p; // current location
- int cursize; // size of current buffer
-
- ublic:
- // Initialize the pointers
- // and the static array.
- extarray()
- {
- base = p = buf;
- end = base + extstartsize;
- cursize = extstartsize;
- }
-
- // If there is a dynamic
- // array, delete it.
- ~extarray()
- {
- if (base != buf)
- delete base;
- }
-
- // Add a character to the array.
- // If it won't fit (along with
- // the null byte) lengthen the
- // array, going into heap memory
- // when necessary.
- void add(char c)
- {
- *p++ = c;
-
- if (p == end)
- {
- char *svp = p;
- char *svbase = base;
- base = new char[cursize + extstartsize];
- memcpy(base, svbase, cursize);
- cursize += extstartsize;
- end = base + cursize;
- p = base + (svp - svbase);
-
- if (svbase != buf)
- delete svbase;
- }
- }
-
- // return the current value
- char *val()
- {
- *p = '\0';
- return base;
- }
-
- // Reset the current pointer to the
- // beginning of the array so that it
- // can be reused.
- void reset()
- {
- p = base;
- }
- ;
-